<template>
  <div>
    <!--    面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    卡片式图区域-->
    <el-card>
<!--      添加角色按钮-->
     <el-row>
       <el-col>
         <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
       </el-col>
     </el-row>
<!--      角色表格-->
      <el-table :data="rolesList" border stripe >
<!--        展开列-->
        <el-table-column type="expand">
          <template scope="scope">
<!--            栅格系统-->
            <el-row
                :class="['bdbottom','vcenter',index1 === 0 ? 'bdtop':'']"
                v-for="(item1,index1) in scope.row.children"
                :key="item1.id">
<!--              一级权限-->
              <el-col :span="5">
                <el-tag class="firstRightTag"
                        @close="removeRightById(scope.row,item1.id)"
                        closable>
                  {{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
<!--              二级和三级权限-->
              <el-col :span="19">
                <el-row
                    :class="[index2 == 0 ? '':'bdtop','vcenter']"
                    v-for="(item2,index2) in item1.children"
                    :key="index2.id">
<!--                  二级权限-->
                  <el-col :span="6">
                    <el-tag type="success"
                            @close="removeRightById(scope.row,item2.id)"
                            closable>
                      {{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
<!--                  三级权限-->
                    <el-col :span="18">
                      <el-tag
                          v-for="(item3,index3) in item2.children"
                          :key="index3"
                          type="warning"
                          @close="removeRightById(scope.row,item3.id)"
                          closable>{{item3.authName}}</el-tag>
                    </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeRoleById(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--    添加角色表单-->
    <el-dialog
        title="添加角色"
        :visible.sync="addRoleDialogVisible"
        width="50%"
        @close="addRoleFormClose">
      <el-form :model="addRoleForm" :rules="addRoleRules" ref="addRoleRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--      底部按钮-->
      <span slot="footer" class="dialog-footer">
            <el-button @click="addRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

<!--    编辑角色表格-->
    <el-dialog
        title="编辑角色信息"
        :visible.sync="editRoleDialogVisible"
        width="50%">
      <el-form :model="editRoleForm" :rules="editRoleRules" ref="editRoleRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--      底部按钮-->
      <span slot="footer" class="dialog-footer">
            <el-button @click="editRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

<!--    分配权限对话框-->
    <el-dialog
        title="分配权限"
        :visible.sync="setRightsDialogVisible" @close="setRightsDialogClose">
      <el-tree :data="rightList"
               :props="treeProps"
               show-checkbox
               node-key="id"
               :default-checked-keys="defKeys"
               ref="treeRef"
               default-expand-all></el-tree>
      <span slot="footer" class="dialog-footer">
            <el-button @click="setRightsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data(){
    return{
      // 角色列表
      rolesList:[],
      // 控制添加角色表单的显示与隐藏
      addRoleDialogVisible:false,
      //添加角色表单
      addRoleForm:{
        roleName:"",
        roleDesc:""
      },
      //添加角色的规则验证
      addRoleRules:{
        roleName:[
            {required:true,message:"角色名称不能为空",trigger:"blur"},
        ],
        roleDesc:[
          {required:true,message:"角色描述不能为空",trigger:"blur"}
        ]
      },
      //控制编辑角色信息表单显示与隐藏
      editRoleDialogVisible:false,
      //编辑角色信息表单
      editRoleForm:{
        roleName:"",
        roleDesc:""
      },
      // 编辑角色信息的验证规则
      editRoleRules:{
        roleName:[
          {required:true,message:"角色名称不能为空",trigger:"blur"},
        ],
        roleDesc:[
          {required:true,message:"角色描述不能为空",trigger:"blur"}
        ]
      },

      //控制分配权限对话框的显示与隐藏
      setRightsDialogVisible:false,
      // 分配权限时的权限列表
      rightList:[],
      // 树形控件的属性绑定对象
      treeProps:{
        label:"authName",
        children:"children",
      },
      //树形控件中默认选中的节点的id值数组
      defKeys:[],
      //分配权限时所需要的角色id
      roleId:''
    }
  },
  methods:{
    //获取角色列表
    async getRolesList(){
      const {data:res} = await this.$http.get("roles")
      if(res.meta.status !== 200){
        return this.$message.error("请求角色列表失败！")
      }
      this.rolesList = res.data
    },

    //添加角色
    addRole(){
      this.$refs.addRoleRef.validate(async (valid)=>{
        if(valid){
        const {data:res} = await this.$http.post("/roles",this.addRoleForm)
          if(res.meta.status !== 201) return this.$message.error("添加角色失败")
          this.$message.success("添加角色成功")
          this.getRolesList()
          this.addRoleDialogVisible = false
        }
      })
    },

    //修改角色信息
    editRole(){
      this.$refs.editRoleRef.validate(async (valid)=>{
        if(valid){
        const {data:res} = await this.$http.put(`roles/${this.editRoleForm.roleId}`,this.editRoleForm)
          if(res.meta.status !== 200){
           return this.$message.error("用户信息修改失败")
          }
        this.$message.success("用户信息修改成功")
        this.getRolesList()
          this.editRoleDialogVisible = false
        }

      })
    },

    // 根据id删除用户
   async removeRoleById(id){
     const confirmResult = await this.$confirm("此操作将永久删除该角色，是否继续？","提示",{
       confirmButtonText: "确定",
       cancelButtonText: "取消",
       type:"warning"
      }).catch((err) => {
       return err
     })
     if(confirmResult === "cancel"){
      return this.$message.info("已取消删除")
     }
     const {data:res} = await this.$http.delete(`/roles/${id}`)
     if(res.meta.status !== 200){
       return this.$message.error("删除角色失败")

     }

     this.$message.success("删除角色成功")
     this.getRolesList()
    },

    //关闭对话框时重置表格
    addRoleFormClose(){
      this.$refs.addRoleRef.resetFields()
    },

    //根据id查询角色信息
   async showEditDialog(id){
      this.editRoleDialogVisible = true
      const {data:res} = await this.$http.get(`/roles/${id}`)
     if(res.meta.status !== 200) return this.$message.error("获取角色信息失败")
     this.editRoleForm = res.data
    },

    //根据id删除权限
    async removeRightById(role,rightId){
     const confirmResult = await this.$confirm("此操作将永久删除该权限，是否继续？","提示",{
        confirmButtonText:"确定",
        cancelButtonText:"取消",
        type:"warning"
      }).catch(err => err)
      if(confirmResult !== "confirm"){
        return this.$message.info("已取消删除")
      }else{
       const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if(res.meta.status !== 200){
          return  this.$message.error("删除权限失败")
        }
        role.children = res.data
      }
    },

    //分配权限
    async showSetRightsDialog(role){
      this.roleId = role.id
      // 获取所有权限
     const {data:res} = await this.$http.get("rights/tree")
      if(res.meta.status !== 200){
        return this.$message.error("获取权限列表失败")
      }
      this.rightList = res.data
      // 获取三级节点id
      this.getLeafKeys(role,this.defKeys)


      this.setRightsDialogVisible = true
    },

    // 使用递归函数，遍历第三级权限id，实现点击分配权限自动勾选已有权限
    getLeafKeys(node,arr){
      // 判断是否有children属性,如果没有则是三级权限
      if(!node.children){
        arr.push(node.id)
        return arr
      }
      node.children.forEach((item)=>{
        this.getLeafKeys(item,arr)
      })
    },
    // 监听分配权限对话框关闭事件
    setRightsDialogClose(){
      this.defKeys = []
    },
    // 点击为角色分配权限
   async allotRights(){
      const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keysStr = keys.join(",")
    const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:keysStr})
     if(res.meta.status !== 200){
       return this.$message.error("分配权限失败")
     }
     this.$message.success("分配权限成功")
     this.getRolesList()
     this.setRightsDialogVisible = false
    }
  },
  mounted(){
    this.getRolesList()
  }


}
</script>

<style scoped>
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.firstRightTag{
  margin-left: 50px!important;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>